package com.mxpio.erp.plm.job;

import com.mxpio.erp.common.plm.entity.ProjectTask;
import com.mxpio.erp.common.plm.service.ProjectTaskService;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Slf4j
@Component
public class ProjectTaskOverdueJob implements Job {

    @Autowired
    private ProjectTaskService projectTaskService;

    /**
     * 对执行状态下的任务，进行逾期天数的计算
     * 逻辑：当前日期大于计划完工时间-逾期
     * 每天计算一次
     */
    @Override
    @Transactional
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info(" --- 计算项目任务逾期天数开始 --- ");
        String[] exStatus = {"20","10"};
        Criteria criteria = Criteria.create().addCriterion("executionStatus", Operator.IN, Arrays.asList(exStatus));
//        criteria.addCriterion("executionStatus", Operator.EQ, "10");
        List<ProjectTask> tasks = projectTaskService.list(ProjectTask.class, criteria);
        for (ProjectTask task : tasks){
            //判断是否逾期
            LocalDate currentDate = LocalDate.now(); //获取当前时间
            Date planEndTime = task.getPlanEndTime();//任务计划完工日期
            LocalDate planEndLocalDate = planEndTime.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate();
            if (currentDate.isAfter(planEndLocalDate)) {
                long daysBetween = ChronoUnit.DAYS.between(planEndLocalDate, currentDate);
                if (daysBetween < 0) {
                    daysBetween = Math.abs(daysBetween);
                }
                String s = String.valueOf(daysBetween);
                task.setOverdueDays(s);//当计划时间超过当前时间时，判断为当前项目延期
            }else {
                task.setOverdueDays("0");//未逾期，逾期天数为0
            }
            projectTaskService.update(task);
        }
        log.info(" --- 计算项目任务逾期天数结束 --- ");
    }
}
